const Router = require("@koa/router");
const { PrismaClient } = require("@prisma/client");
const router = new Router({ prefix: "/users" });
const prisma = new PrismaClient();

// 获取用户列表
router.get("/", async (ctx) => {
  const users = await prisma.users.findMany();
  ctx.body = users;
});

// 新增用户
router.post("/", async (ctx) => {
  try {
    const { account, gender, avatar, bio, nickname, password, birth_timestamp_second, isVip, vip_expiration_timestamp_second, has_trial_used } = ctx.request.body;

    // 基础验证
    if (!account || !nickname || !password) {
      ctx.status = 400;
      ctx.body = { success: false, message: "账号、昵称和密码是必填项" };
      return;
    }

    // 检查账号是否已存在
    const existingUserByAccount = await prisma.users.findFirst({
      where: { account },
    });
    if (existingUserByAccount) {
      ctx.status = 400;
      ctx.body = { success: false, message: "账号已存在" };
      return;
    }

    const newUser = await prisma.users.create({
      data: {
        account,
        gender,
        avatar,
        bio,
        nickname,
        password: password,
        birth_timestamp_second,
        isVip,
        vip_expiration_timestamp_second,
        has_trial_used,
        created_at: new Date(), // Prisma 会处理默认值，但明确设置也可以
      },
    });
    // 从返回结果中移除密码
    const { password: _, ...userWithoutPassword } = newUser;
    ctx.status = 201; // 201 Created
    ctx.body = { success: true, data: userWithoutPassword };
  } catch (err) {
    console.error("新增用户失败:", err);
    ctx.status = 500;
    ctx.body = { success: false, message: err.message };
  }
});

// 修改用户信息
router.put("/:id", async (ctx) => {
  try {
    const id = parseInt(ctx.params.id, 10);
    if (isNaN(id)) {
      ctx.status = 400;
      ctx.body = { success: false, message: "ID 必须是有效的整数" };
      return;
    }
    const { gender, avatar, bio, nickname, birth_timestamp_second, isVip, vip_expiration_timestamp_second, has_trial_used } = ctx.request.body;
    const updateData = {};
    if (gender !== undefined) updateData.gender = gender;
    if (avatar !== undefined) updateData.avatar = avatar;
    if (bio !== undefined) updateData.bio = bio;
    if (nickname !== undefined) updateData.nickname = nickname;
    if (birth_timestamp_second !== undefined) updateData.birth_timestamp_second = birth_timestamp_second;
    if (isVip !== undefined) updateData.isVip = isVip;
    if (vip_expiration_timestamp_second !== undefined) updateData.vip_expiration_timestamp_second = vip_expiration_timestamp_second;
    if (has_trial_used !== undefined) updateData.has_trial_used = has_trial_used;
    if (Object.keys(updateData).length === 0) {
      ctx.status = 400;
      ctx.body = { success: false, message: "没有提供需要更新的数据" };
      return;
    }

    const updatedUser = await prisma.users.update({
      where: { id },
      data: updateData,
    });
    const { password: _, ...userWithoutPassword } = updatedUser;
    ctx.body = { success: true, data: userWithoutPassword };
  } catch (err) {
    console.error("修改用户信息失败:", err);
    ctx.status = 500;
    ctx.body = { success: false, message: err.message };
  }
});

module.exports = router;
